<script setup lang="ts">
import { ref, onMounted, computed } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { VideoCamera, Search, Plus, Edit, Delete, User, Picture } from '@element-plus/icons-vue'
import request from '@/utils/request'

// 响应式数据
const loading = ref(false)
const channels = ref<any[]>([])
const currentPage = ref(1)
const pageSize = ref(20)
const total = ref(0)
const search = ref('')

// 对话框状态
const showDialog = ref(false)
const showCreateDialog = ref(false)
const editing = ref(false)
const saving = ref(false)
let currentId: string | null = null

// 表单数据
const form = ref({
  name: '',
  description: '',
  avatarUrl: '',
  isActive: true
})

// API基础URL
const API_BASE_URL = (import.meta as any)?.env?.VITE_API_BASE_URL || ''

// 计算属性
const hasChannels = computed(() => channels.value.length > 0)
const isSearching = computed(() => search.value.trim().length > 0)

// 获取채널列表
const fetchChannels = async () => {
  loading.value = true
  try {
    const params: any = {
      page: currentPage.value,
      limit: pageSize.value
    }
    if (search.value.trim()) {
      params.search = search.value.trim()
    }

    const response = await request.get('/api/admin/channels', { params })
    channels.value = response.data.channels || []
    total.value = response.data.total || 0
  } catch (error) {
    console.error('채널 목록 가져오기 실패:', error)
    ElMessage.error('채널 목록을 가져오는데 실패했습니다')
  } finally {
    loading.value = false
  }
}

// 搜索处理
const handleSearch = () => {
  currentPage.value = 1
  fetchChannels()
}

// 清空搜索
const clearSearch = () => {
  search.value = ''
  currentPage.value = 1
  fetchChannels()
}

// 打开创建对话框
const openCreate = () => {
  editing.value = false
  currentId = null
  form.value = {
    name: '',
    description: '',
    avatarUrl: '',
    isActive: true
  }
  showCreateDialog.value = true
}

// 打开编辑对话框
const openEdit = (row: any) => {
  editing.value = true
  currentId = String(row.id)
  form.value = {
    name: row.name,
    description: row.description || '',
    avatarUrl: row.avatarUrl || '',
    isActive: !!row.isActive
  }
  showCreateDialog.value = true
}

// 处理图片上传成功
const handleCoverSuccess = (res: any) => {
  if (res?.coverUrl) {
    form.value.avatarUrl = res.coverUrl
    ElMessage.success('이미지 업로드 성공')
  }
}

// 处理图片上传失败
const handleCoverError = () => {
  ElMessage.error('이미지 업로드 실패')
}

// 保存채널
const save = async () => {
  if (!form.value.name.trim()) {
    ElMessage.error('채널 이름을 입력해주세요')
    return
  }

  saving.value = true
  try {
    if (editing.value && currentId) {
      await request.put(`/api/admin/channels/${currentId}`, form.value)
      ElMessage.success('채널 수정 성공')
    } else {
      await request.post('/api/admin/channels', form.value)
      ElMessage.success('채널 생성 성공')
    }
    showCreateDialog.value = false
    fetchChannels()
  } catch (error) {
    console.error('채널 저장 실패:', error)
    ElMessage.error(editing.value ? '채널 수정 실패' : '채널 생성 실패')
  } finally {
    saving.value = false
  }
}

// 删除채널
const deleteChannel = async (row: any) => {
  try {
    await ElMessageBox.confirm(
      '이 채널을 삭제하시겠습니까?\n주의: 채널에 연결된 비디오나 라이브 방이 있으면 삭제할 수 없습니다.',
      '삭제 확인',
      {
        confirmButtonText: '삭제',
        cancelButtonText: '취소',
        type: 'warning',
        dangerouslyUseHTMLString: true
      }
    )

    row.deleting = true
    await request.delete(`/api/admin/channels/${row.id}`)
    ElMessage.success('채널 삭제 성공')
    fetchChannels()
  } catch (error) {
    if (error !== 'cancel') {
      console.error('채널 삭제 실패:', error)
      ElMessage.error('채널 삭제 실패')
    }
  } finally {
    row.deleting = false
  }
}

// 页面变化处理
const handlePageChange = (page: number) => {
  currentPage.value = page
  fetchChannels()
}

// 组件挂载时获取数据
onMounted(() => {
  fetchChannels()
})
</script>

<template>
  <div class="mobile-channel-management">
    <!-- 搜索栏 -->
    <div class="mobile-search-section">
      <el-input
        v-model="search"
        placeholder="채널명 검색"
        :prefix-icon="Search"
        clearable
        @keyup.enter="handleSearch"
        @clear="clearSearch"
      >
        <template #append>
          <el-button :icon="Search" @click="handleSearch" :loading="loading" />
        </template>
      </el-input>
    </div>

    <!-- 操作按钮 -->
    <div class="mobile-action-section">
      <el-button type="primary" :icon="Plus" @click="openCreate" size="large" style="width: 100%;">
        채널 생성
      </el-button>
    </div>

    <!-- 채널 列表 -->
    <div class="mobile-channels-list" v-loading="loading">
      <!-- 空状态 -->
      <div v-if="!hasChannels && !loading" class="mobile-empty">
        <el-icon class="mobile-empty-icon" size="48">
          <VideoCamera />
        </el-icon>
        <div class="mobile-empty-text">
          {{ isSearching ? '검색 결과가 없습니다' : '채널이 없습니다' }}
        </div>
        <el-button v-if="!isSearching" type="primary" :icon="Plus" @click="openCreate" style="margin-top: 16px;">
          첫 번째 채널 생성
        </el-button>
      </div>

      <!-- 채널 卡片列表 -->
      <div v-else class="channel-cards">
        <div v-for="channel in channels" :key="channel.id" class="mobile-channel-card">
          <!-- 채널 头像和基本信息 -->
          <div class="channel-header">
            <div class="channel-avatar">
              <img
                v-if="channel.avatarUrl"
                :src="`${API_BASE_URL}${channel.avatarUrl}`"
                alt="채널 아바타"
                class="avatar-image"
              />
              <el-icon v-else class="avatar-placeholder" size="32">
                <User />
              </el-icon>
            </div>
            <div class="channel-info">
              <div class="channel-name">{{ channel.name }}</div>
              <div class="channel-description">{{ channel.description || '설명 없음' }}</div>
              <div class="channel-meta">
                <el-tag :type="channel.isActive ? 'success' : 'info'" size="small">
                  {{ channel.isActive ? '활성' : '비활성' }}
                </el-tag>
                <span class="channel-id">ID: {{ channel.id }}</span>
              </div>
            </div>
          </div>

          <!-- 操作按钮 -->
          <div class="channel-actions">
            <el-button
              :icon="Edit"
              size="small"
              @click="openEdit(channel)"
              :disabled="channel.deleting"
            >
              편집
            </el-button>
            <el-button
              :icon="Delete"
              size="small"
              type="danger"
              @click="deleteChannel(channel)"
              :loading="channel.deleting"
            >
              삭제
            </el-button>
          </div>
        </div>
      </div>
    </div>

    <!-- 分页 -->
    <div v-if="total > pageSize" class="mobile-pagination">
      <el-pagination
        v-model:current-page="currentPage"
        :page-size="pageSize"
        :total="total"
        layout="prev, pager, next"
        @current-change="handlePageChange"
        small
      />
    </div>

    <!-- 创建/编辑 채널 对话框 -->
    <el-dialog
      v-model="showCreateDialog"
      :title="editing ? '채널 편집' : '채널 생성'"
      width="95%"
      :close-on-click-modal="false"
      class="mobile-dialog"
    >
      <el-form :model="form" label-position="top" class="mobile-form">
        <el-form-item label="채널 이름" required>
          <el-input
            v-model="form.name"
            placeholder="채널 이름을 입력하세요"
            maxlength="50"
            show-word-limit
          />
        </el-form-item>

        <el-form-item label="채널 설명">
          <el-input
            v-model="form.description"
            type="textarea"
            :rows="3"
            placeholder="채널 설명을 입력하세요"
            maxlength="200"
            show-word-limit
          />
        </el-form-item>

        <el-form-item label="프로필 이미지">
          <div class="mobile-upload-section">
            <el-upload
              class="mobile-uploader"
              :action="`${API_BASE_URL}/api/admin/uploads/cover`"
              name="cover-upload"
              :with-credentials="true"
              :show-file-list="false"
              :on-success="handleCoverSuccess"
              :on-error="handleCoverError"
              accept="image/*"
            >
              <div class="upload-area">
                <img
                  v-if="form.avatarUrl"
                  :src="`${API_BASE_URL}${form.avatarUrl}`"
                  class="uploaded-image"
                  alt="업로드된 이미지"
                />
                <div v-else class="upload-placeholder">
                  <el-icon size="32">
                    <Picture />
                  </el-icon>
                  <div class="upload-text">이미지 선택</div>
                </div>
              </div>
            </el-upload>
            <div class="upload-tips">
              <p>• 권장 크기: 200x200px</p>
              <p>• 지원 형식: JPG, PNG, GIF</p>
              <p>• 최대 크기: 5MB</p>
            </div>
          </div>
        </el-form-item>

        <el-form-item label="활성화 상태">
          <el-switch
            v-model="form.isActive"
            active-text="활성"
            inactive-text="비활성"
          />
        </el-form-item>
      </el-form>

      <template #footer>
        <div class="mobile-dialog-footer">
          <el-button @click="showCreateDialog = false" size="large">취소</el-button>
          <el-button
            type="primary"
            @click="save"
            :loading="saving"
            size="large"
          >
            {{ editing ? '수정' : '생성' }}
          </el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<style scoped>
/* 移动端채널管理主容器 */
.mobile-channel-management {
  display: flex;
  flex-direction: column;
  gap: 16px;
  height: 100%;
}

/* 搜索区域 */
.mobile-search-section {
  background: var(--el-bg-color);
  padding: 16px;
  border-radius: 12px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.04);
}

/* 操作按钮区域 */
.mobile-action-section {
  padding: 0 16px;
}

/* 채널列表容器 */
.mobile-channels-list {
  flex: 1;
  overflow-y: auto;
  -webkit-overflow-scrolling: touch;
}

/* 空状态 */
.mobile-empty {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 60px 20px;
  color: var(--el-text-color-placeholder);
  text-align: center;
}

.mobile-empty-icon {
  color: var(--el-color-info);
  margin-bottom: 16px;
}

.mobile-empty-text {
  font-size: 16px;
  margin-bottom: 8px;
}

/* 채널卡片容器 */
.channel-cards {
  display: flex;
  flex-direction: column;
  gap: 12px;
  padding: 0 16px;
}

/* 移动端채널卡片 */
.mobile-channel-card {
  background: var(--el-bg-color);
  border: 1px solid var(--el-border-color-lighter);
  border-radius: 12px;
  padding: 16px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.04);
  transition: all 0.3s ease;
}

.mobile-channel-card:active {
  transform: scale(0.98);
  box-shadow: 0 1px 4px rgba(0, 0, 0, 0.08);
}

/* 채널头部信息 */
.channel-header {
  display: flex;
  align-items: flex-start;
  gap: 12px;
  margin-bottom: 16px;
}

.channel-avatar {
  width: 48px;
  height: 48px;
  border-radius: 50%;
  overflow: hidden;
  background: var(--el-fill-color-light);
  display: flex;
  align-items: center;
  justify-content: center;
  flex-shrink: 0;
}

.avatar-image {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.avatar-placeholder {
  color: var(--el-text-color-placeholder);
}

.channel-info {
  flex: 1;
  min-width: 0;
}

.channel-name {
  font-size: 16px;
  font-weight: 600;
  color: var(--el-text-color-primary);
  margin-bottom: 4px;
  word-break: break-word;
}

.channel-description {
  font-size: 14px;
  color: var(--el-text-color-regular);
  margin-bottom: 8px;
  word-break: break-word;
  line-height: 1.4;
}

.channel-meta {
  display: flex;
  align-items: center;
  gap: 8px;
  flex-wrap: wrap;
}

.channel-id {
  font-size: 12px;
  color: var(--el-text-color-placeholder);
}

/* 채널操作按钮 */
.channel-actions {
  display: flex;
  gap: 8px;
  justify-content: flex-end;
}

.channel-actions .el-button {
  min-width: 60px;
}

/* 分页 */
.mobile-pagination {
  display: flex;
  justify-content: center;
  padding: 16px;
  background: var(--el-bg-color);
  border-radius: 12px;
  margin: 0 16px;
}

/* 移动端对话框样式 */
.mobile-dialog {
  margin: 5vh auto;
}

.mobile-form {
  padding: 0;
}

.mobile-form .el-form-item {
  margin-bottom: 20px;
}

.mobile-form .el-form-item__label {
  font-weight: 600;
  color: var(--el-text-color-primary);
  margin-bottom: 8px;
}

/* 移动端上传组件 */
.mobile-upload-section {
  width: 100%;
}

.mobile-uploader {
  width: 100%;
}

.upload-area {
  width: 120px;
  height: 120px;
  border: 2px dashed var(--el-border-color);
  border-radius: 12px;
  display: flex;
  align-items: center;
  justify-content: center;
  cursor: pointer;
  transition: all 0.3s ease;
  overflow: hidden;
}

.upload-area:hover {
  border-color: var(--el-color-primary);
  background: var(--el-color-primary-light-9);
}

.uploaded-image {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.upload-placeholder {
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 8px;
  color: var(--el-text-color-placeholder);
}

.upload-text {
  font-size: 14px;
}

.upload-tips {
  margin-top: 12px;
  font-size: 12px;
  color: var(--el-text-color-placeholder);
  line-height: 1.5;
}

.upload-tips p {
  margin: 0;
}

/* 移动端对话框底部 */
.mobile-dialog-footer {
  display: flex;
  gap: 12px;
  padding: 16px 0 0 0;
}

.mobile-dialog-footer .el-button {
  flex: 1;
}

/* 暗黑模式适配 */
:root.dark .mobile-channel-card {
  background: var(--el-bg-color);
  border-color: var(--el-border-color);
}

:root.dark .upload-area {
  border-color: var(--el-border-color);
}

:root.dark .upload-area:hover {
  border-color: var(--el-color-primary);
  background: var(--el-color-primary-dark-2);
}
</style>
